# -*- coding: utf-8 -*-
from json_files import json_files
import subprocess


def run_cmd_Popen_PIPE(cmd_string):
    # print('运行cmd指令：{}'.format(cmd_string))
    rea = subprocess.Popen(cmd_string, env=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='gbk',
                           creationflags=0x08000000)
    res = rea.stdout.read()
    reb = rea.stderr.read()
    print(reb)
    return res


# 生成生成cer文件
def cer_ap(csr_files='', p12_files='./lib/OpenHarmony.p12', app1_key='z1', key_pwd='openharmony666', keystore_Pwd='123456',
           subCA_File='./lib/subCA.cer', rootCA_File='./lib/rootCA.cer', outFile='./out/z1.cer',  in_cc='CN', in_oa='OpenHarmony',
           in_ou='OpenHarmony Team', in_cn='OpenHarmony Application CA', in_key='"openharmony application ca"', in_cnn='OpenHarmony Application Release'):
    print('生成应用签名证书：')
    if csr_files == '':
        # 生成cer证书方法1，需要openharmony.p12文件+存在于openharmony.p12内的证书名和密码。
        info = run_cmd_Popen_PIPE(
            'java -jar hap-sign-tool.jar generate-app-cert -keyAlias ' + app1_key + ' -signAlg "SHA256withECDSA"  -issuer '
            '"C=' + in_cc + ',O=' + in_oa + ',OU=' + in_ou + ',CN= ' + in_cn + '" -issuerKeyAlias ' + in_key + ''
            ' -subject "C=' + in_cc + ',O=' + in_oa + ',OU=' + in_ou + ',CN=' + in_cnn + '" -keystoreFile ' + p12_files + ''
            ' -subCaCertFile '+subCA_File+' -rootCaCertFile '+rootCA_File+' -outForm "certChain" -outFile '+outFile+' -keyPwd ' + key_pwd + ' -keystorePwd '
            + keystore_Pwd + ' -issuerKeyPwd '+keystore_Pwd+' -validity "365"')
    else:
        # 生成cer证书的方法2，需要csr证书请求文件和openharmony.p12文件。
        info = run_cmd_Popen_PIPE('keytool -gencert -alias "OpenHarmony Application CA" -infile '
                                  + csr_files + ' -outfile ./out/z1.cer '
                                                '-keystore '
                                                './lib/OpenHarmony.p12 -sigAlg '
                                                'SHA384withECDSA '
                                                '-storepass 123456 '
                                                '-ext KeyUsage:"critical'
                                                '=digitalSignature" '
                                                '-validity 3650 -rfc')
    return info


# 生成p7b文件
def p7b_ap(hap, keyAlias='"openharmony application profile release"', keystore_Pwd='123456',  p12_File='./lib/OpenHarmony.p12', cer_File='./lib/Release.pem', outFile='./out/app1-profile.p7b', releases_json='./lib/Release.json'):
    # 调用函数修改UnsgnedReleasedProfileTemplate.json文件并保存到Release.json
    json_files(hap)
    print('\n为应用生成p7b文件：')
    info = run_cmd_Popen_PIPE(
        'java -jar hap-sign-tool.jar  sign-profile -keyAlias ' + keyAlias + ' '
        '-signAlg "SHA256withECDSA" -mode "localSign" -profileCertFile ' + cer_File + ' -inFile '
        + releases_json + ' -keystoreFile ' + p12_File + ' -outFile ' + outFile + ' -keyPwd ' + keystore_Pwd +
                          ' -keystorePwd ' + keystore_Pwd)
    return info


# 签名hap文件
def hap_ap(hap_files='./iut/a1.hap', p7b_files='./out/app1-profile.p7b', cer_files='./out/z1.cer',
           p12_files='./lib/OpenHarmony.p12',
           key_alias='z1', key_pwd='openharmony666', keystore_pwd='123456'):
    print('签名hap：')
    info = run_cmd_Popen_PIPE(
        'java -jar hap-sign-tool.jar sign-app -keyAlias ' + key_alias + ' -signAlg "SHA256withECDSA" -mode'
        ' "localSign" -appCertFile ' + cer_files + ' -profileFile ' + p7b_files + ' -inFile ' + hap_files
        + ' -keystoreFile ' + p12_files + ' -outFile "./out/app1-signed.hap" -keyPwd ' + key_pwd +
        ' -keystorePwd ' + keystore_pwd)
    return info


def hdc_device():
    print('OpenHarmony设备：\nList of targets attached:\n' + run_cmd_Popen_PIPE('hdc list targets'))
    print('HarmonyOS设备：\n' + run_cmd_Popen_PIPE('./lib/HdcExternal.exe list targets'))


def add_key(key='', pwd=''):
    print('给密钥库添加密钥：')
    info = run_cmd_Popen_PIPE(
        'java -jar hap-sign-tool.jar generate-keypair -keyAlias ' + key + ' -keyAlg "ECC"  -keySize "NIST-P-256" -keystoreFile "./lib/OpenHarmony.p12" -keyPwd  ' + pwd + ' -keystorePwd "123456"')
    return info


# 安装hap文件
def hap_install(hdc=0, hap_files='./iut/a1.hap'):
    print('安装hap：')
    if hdc == 0:
        info = run_cmd_Popen_PIPE('hdc app install ' + hap_files)
        return info
    else:
        if hdc == 1:
            info = run_cmd_Popen_PIPE('./lib/HdcExternal.exe app install ' + hap_files)
            return info

# cer_ap()
# p7b_ap()
# hap_ap()
# hap_install()
